<?php namespace App\Http\Controllers\Api\Admin;

use App\AboutUs;
use App\Admin;
use App\AiRecord;
use App\AiScoreRule;
use App\AppointExpert;
use App\Banner;
use App\BooksChapter;
use App\BooksInfo;
use App\Classify;
use App\Comment;
use App\CommentLike;
use App\DemandAllureLabel;
use App\DemandButt;
use App\DemandButtCaseImg;
use App\DemandImg;
use App\Demands;
use App\Experts;
use App\Group;
use App\GroupXUser;
use App\Http\Controllers\Api\ImageController;
use App\Http\Controllers\Controller;
use App\Http\Services\AdminManager;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Http\Services\Wechat\WechatModelMsg;
use App\Images;
use App\Industries;
use App\Jobs\sendModelMsg;
use App\Jobs\syncWXMaterial;
use App\Message;
use App\MessageRemind;
use App\MessageXUser;
use App\News;
use App\NewsLabel;
use App\NewsXDemand;
use App\PersonalAuth;
use App\RechargePackage;
use App\SysSetUp;
use App\UnitAuth;
use App\Units;
use App\UnitSettledApply;
use App\User;
use App\UserInfo;
use App\UserXUnit;
use App\VipPackageXRule;
use App\VipRule;
use Auth;
use Illuminate\Http\Request;
use Log;

class SystemController extends Controller
{
    //需求
    /**@author cmj
     * 获取需求列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDemandList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $selectType = 3;
        $userIds = [];
        if ($adminUser->role == 0){
            $selectType = 1;

            $unitAuth = CommonManager::isUnitAuth($adminUser->id);
            if($unitAuth){
                $userXUnit = UserXUnit::whereUserId($adminUser->id)->first();
                if($userXUnit){
                    if($userXUnit->is_admin == 1){
                        $selectType = 2;
                        $userIds = UserXUnit::whereUnitId($userXUnit->unit_id)->pluck('user_id');
                    }
                }
            }
        }

        $status     =$request->get('status');
        $review     =$request->get('review');
        $is_shop    =$request->get('is_shop');
//        $is_official=$request->get('is_official');
        $keyword    =$request->get('keyword');
        $start_time =$request->get('start_time');
        $end_time   =$request->get('end_time');
        $page   =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit  =!is_null($request->get('limit')) ? $request->get('limit') : 10;
        $id     =$request->get('id');
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
        if($selectType == 3){
            $demand   = Demands::whereNull('deleted_at');
            if($id != 0){
                $demand = $demand->whereId($id);
            }
        }elseif($selectType == 2){
            $demand   = Demands::whereNull('deleted_at');
        }elseif($selectType == 1){
            $demand   = Demands::whereNull('deleted_at');
        }

        if (trim($keyword)){
            $demand=$demand ->where('title','like','%'.trim($keyword).'%')
                            ->orWhere('content','like','%'.trim($keyword).'%');
        }
//        if ($adminUser->role==0)
//            $demand=$demand->whereUserId($adminUser->id);
        if ($status){
            if ($status==1)
                $demand=$demand->whereStatus(1);
            else if ($status==2)
                $demand=$demand->whereStatus(0);
        }
        if ($review){
            if ($review==1 || $review==2)
                $demand=$demand->whereReview($review);
            else if ($review==3)
                $demand=$demand->whereReview(0);
        }
        if ($is_shop){
            if ($is_shop==1)
                $demand=$demand->whereIsShop(1);
            else
                $demand=$demand->whereIsShop(0);
        }
        if ($start_time && $end_time){
            $demand=$demand->whereBetween('created_at',[$start_time,$end_time]);
        }

        if($selectType == 2){
            $demand   = $demand->whereIn('user_id',$userIds);
        }elseif($selectType == 1){
            $demand = $demand->whereUserId($adminUser->id);
        }

        $page_info['total'] =$demand->count();

        if($selectType == 3){
            $demands            =$demand->orderBy('is_top','desc')->orderBy('created_at','desc')->offset($page * $limit)->limit($limit)->get();
        }else{
            $demands            =$demand->orderBy('created_at','desc')->offset($page * $limit)->limit($limit)->get();
        }

        if (count($demands) > 0){
            foreach ($demands as $item){
                $item->user_info    =CommonManager::getUserBasicInfo($item->user_id);
                $classify           =Classify::whereId($item->classify_id)->first();
                $item->classify_name=$classify ? $classify->name : '其它（该分类已被删除）';
                $newComment =Comment::whereDemandId($item->id)->whereStatus(0)->first();
                $item->new_comment  = $newComment ? 1: 0;

                $item->wxapp_qr_code_url = url('images/renxieqrcode.jpg');
            }
        }

        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$demands]);

    }

    /**@author cmj
     * 用户获取已对接的需求列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDockDemandList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

//        $selectType = 3;
//        $userIds = [];
//        if ($adminUser->role == 0){
//            $selectType = 1;
//
//            $unitAuth = CommonManager::isUnitAuth($adminUser->id);
//            if($unitAuth){
//                $userXUnit = UserXUnit::whereUserId($adminUser->id)->first();
//                if($userXUnit){
//                    if($userXUnit->is_admin == 1){
//                        $selectType = 2;
//                        $userIds = UserXUnit::whereUnitId($userXUnit->unit_id)->pluck('user_id');
//                    }
//                }
//            }
//        }

        $status     =$request->get('status');
        $review     =$request->get('review');
        $is_shop    =$request->get('is_shop');
//        $is_official=$request->get('is_official');
        $keyword    =$request->get('keyword');
        $start_time =$request->get('start_time');
        $end_time   =$request->get('end_time');
        $page   =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit  =!is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
//        if($selectType == 3){
//            $demand   = Demands::whereNull('deleted_at');
//        }elseif($selectType == 2){
//            $demand   = Demands::whereIn('user_id',$userIds);
//        }elseif($selectType == 1){
//            $demand   = Demands::whereUserId($adminUser->id);
//        }
        $demand_ids = DemandButt::whereUserId($adminUser->id)->pluck('demand_id')->toArray();

        $demand=Demands::whereNull('deleted_at');
        if (trim($keyword)){
            $demand=$demand ->where('title','like','%'.trim($keyword).'%')
                            ->orWhere('content','like','%'.trim($keyword).'%');
        }
        $demand     = $demand->whereIn('id',$demand_ids);
//        if ($adminUser->role==0)
//            $demand=$demand->whereUserId($adminUser->id);
        if ($status){
            if ($status==1)
                $demand=$demand->whereStatus(1);
            else if ($status==2)
                $demand=$demand->whereStatus(0);
        }
        if ($review){
            if ($review==1 || $review==2)
                $demand=$demand->whereReview($review);
            else if ($review==3)
                $demand=$demand->whereReview(0);
        }
        if ($is_shop){
            if ($is_shop==1)
                $demand=$demand->whereIsShop(1);
            else
                $demand=$demand->whereIsShop(0);
        }
        if ($start_time && $end_time){
            $demand=$demand->whereBetween('created_at',[$start_time,$end_time]);
        }
        $page_info['total'] =$demand->count();

        $demands            =$demand->orderBy('created_at','desc')->offset($page * $limit)->limit($limit)->get();

        if (count($demands) > 0){
            foreach ($demands as $item){
                $item->user_info    =CommonManager::getUserBasicInfo($item->user_id);
                $classify           =Classify::whereId($item->classify_id)->first();
                $item->classify_name=$classify ? $classify->name : '其它（该分类已被删除）';
                $newComment =Comment::whereDemandId($item->id)->whereStatus(0)->first();
                $item->new_comment  = $newComment ? 1: 0;
            }
        }

        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$demands]);

    }

    /**
     * 审核需求
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function reviewDemand(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//        if ($adminUser->role==0)
//            return response()->json(['level' => 'error','message' => '您的权限不足！','data' => 'error']);
        $id     =$request->get('demand_id');
        $type   =$request->get('type');
        $remark = $request->get('remark');
        $demand =Demands::whereId($id)->first();
        if (!$demand)
            return response()->json(['level'=>'error','message'=>'服务不存在','data'=>[]]);
        if ($type==1 || $type==2){
            $demand->review =$type;
            if ($type==1){
                $demand->is_shop=1;

                //是否置顶需求
                $isTop = 0;
                $stickyDemandVipRule = VipRule::whereMark('sticky_demand')->first();
                if($stickyDemandVipRule){
                    $userBindVipPackageList = CommonManager::judgeVipPackageXRule($stickyDemandVipRule->id,$demand->user_id);
                    if($userBindVipPackageList){
                        $isTop = 1;
                    }
                }

                if($isTop == 1){
                    $demand->is_top = 1;
                }else{
                    $demand->is_top = 0;
                }
                $user = User::whereId($demand->user_id)->first();
                if($user){
                    WechatLogin::weSendSubscribeMessage('content_auth_result',$user->wx_openid,0,$demand->title,'通过',date('Y-m-d H:i:s',time()),$remark);
                }
            }else{
                $user = User::whereId($demand->user_id)->first();
                if($user){
                    WechatLogin::weSendSubscribeMessage('content_auth_result',$user->wx_openid,0,$demand->title,'拒绝',date('Y-m-d H:i:s',time()),$remark);
                }
            }
            $demand->save();
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$demand]);
        } else {
            return response()->json(['level'=>'error','message'=>'参数错误','data'=>$demand]);
        }

    }

    /**
     * 获取对接这个需求的用户列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDemandButtList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $demand_id  =$request->get('demand_id');
        $status     =$request->get('status');
        $page       =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit      =!is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
        /** @var DemandButt $item */
        $demandButt=DemandButt::whereDemandId($demand_id);
        if ($status){
            if ($status==1 || $status==2)
                $demandButt=$demandButt->whereStatus($status);
            else if ($status==3)
                $demandButt=$demandButt->whereStatus(0);
        }
        $page_info['total']=$demandButt->count();
        $demandButt=$demandButt->offset($page * $limit)->limit($limit)->get();
        if (count($demandButt) > 0){
            foreach ($demandButt as $item){
                $item->user_info    =CommonManager::getUserBasicInfo($item->user_id);

                $caseImgList = DemandButtCaseImg::whereDemandButtId($item->id)->get();
                if(count($caseImgList) > 0){
                    foreach($caseImgList as $caseImg){
                        $caseImg->img_url = FileManager::getImgUrl($caseImg->img_id);
                    }
                }

                $item->case_img_list = $caseImgList;

                if($item->status == 0){
                    $item->status_name = '筛选中';
                }elseif($item->status == 1){
                    $item->status_name = '通过';
                }elseif($item->status == 2){
                    $item->status_name = '拒绝';
                }else{
                    $item->status_name = '未知';
                }
            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$demandButt]);

    }

    /**
     * 需求操作对接者
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function operateDemandButt(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $demand_id  =$request->get('demand_id');
        $user_id    =$request->get('user_id');
        $type       =$request->get('type');
        $demand=Demands::whereId($demand_id)->first();
        if (!$demand)
            return response()->json(['level'=>'error','message'=>'服务不存在','data'=>[]]);
//        if ($demand->user_id!==$user->id)
//            return response()->json(['level'=>'error','message'=>'该需求不是您发布的，不能操作']);

        $demand_butt=DemandButt::whereDemandId($demand_id)->whereUserId($user_id)->whereStatus(0)->first();
        if (!$demand_butt)
            return response()->json(['level'=>'error','message'=>'已经操作过了','data'=>[]]);

        if ($type==1){
            $demand->status=1;
            $demand->save();
            $demand_butt->status=1;
            $demand_butt->save();
            return response()->json(['level'=>'success','message'=>'接受成功','data'=>'success']);
        } else if ($type==2){
//            $demand->status=2;
//            $demand->save();
            $demand_butt->status=2;
            $demand_butt->save();
            return response()->json(['level'=>'success','message'=>'淘汰成功','data'=>'success']);
        } else {
            return response()->json(['level'=>'error','message'=>'参数type错误','data'=>'error']);
        }

    }

    /**
     * 需求上下架
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setDemandShopStatus(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $demand_id  =$request->get('demand_id');
        $status    =$request->get('status');

        $demand     =Demands::whereId($demand_id)->first();
        if (!$demand)
            return response()->json(['level'=>'error','message'=>'服务不存在']);
        $message='系统错误';
        if ($status==1){
            $demand->is_shop =1;
            $message='上架成功';
        } else if($status==2){
            $demand->is_shop =0;
            $message='下架成功';
        } else
            return response()->json(['level'=>'error','message'=>'参数错误']);

        $demand->save();
        return response()->json(['level'=>'success','message'=>$message]);
    }

    /**
     * 发布需求
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendDemandByAdmin(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

//        if ((int)$adminUser->role !== 0)
//            return response()->json(['level' => 'error','message' => '无法发布']);
//
//        $isunitAuth = CommonManager::isUnitAuth($adminUser->id);
//        if(!$isunitAuth)
//            return response()->json(['level' => 'error','message' => '请先进行单位认证']);

//        //是否有发布需求权益
//        $releaseDemand = 3;
//        $releaseDemandVipRule = VipRule::whereMark('release_demand')->first();
//        if($releaseDemandVipRule){
//            $userBindVipPackageList = CommonManager::judgeVipPackageXRule($releaseDemandVipRule->id,$adminUser->id);
//            if($userBindVipPackageList){
//                $releaseDemand = 0;
//                $userBindVipPackageList = CommonManager::getUserBindVipPackageInfo($adminUser->id);
//                if(count($userBindVipPackageList) > 0){
//                    foreach($userBindVipPackageList as $userBindVipPackage){
//                        if(!empty($userBindVipPackage->vip_package_info)){
//                            $vipPackageXRule = VipPackageXRule::whereVipPackageId($userBindVipPackage->vip_package_info->id)->whereVipRuleId($releaseDemandVipRule->id)->first();
//                            if($vipPackageXRule){
//                                $releaseDemand += $vipPackageXRule->today_run_num;
//                            }
//                        }
//                    }
//                }
//            }
//        }

        //每日开始时间和结结束时间
//        $todayStartTime = date("Y-m-d 00:00:00",time());
//        $todayEndTime   = date("Y-m-d 23:59:59",time());
//
//        $todayReleaseDemandNum = Demands::whereUserId($adminUser->id)->whereBetween('created_at',[$todayStartTime,$todayEndTime])->count();
//        if($todayReleaseDemandNum >= $releaseDemand)
//            return response()->json(['level' => 'error','message' => '发布次数已用尽']);

        $title      =$request->get('title');
        $content    =$request->get('content');
        $recruitment=$request->get('recruitment');
        $salary     =$request->get('salary');
        $education  =$request->get('education');
        $first_arrive_time  =$request->get('first_arrive_time');
        $last_arrive_time   =$request->get('last_arrive_time');
        $start_time         =$request->get('start_time');
        $end_time           =$request->get('end_time');
        $classify_id        =$request->get('classify_id');
        $province           =$request->get('province');
        $city               =$request->get('city');
        $area               =$request->get('area');
        $address            =$request->get('address');
        $industry           =$request->get('industry_id');
        $img_ids            =$request->get('img_ids');
        $label_arr          =$request->get('label_arr');
        $is_show_publisher  =!is_null($request->get('is_show_publisher')) ? $request->get('is_show_publisher') : 0;
        $isAssociationDocking  =!is_null($request->get('is_association_docking')) ? $request->get('is_association_docking') : 0;
        $maxButtingNum         =!is_null($request->get('max_butting_num')) ? $request->get('max_butting_num') : 0;
        $budget                =!is_null($request->get('budget')) ? $request->get('budget') : '';

        if (!$title)
            return response()->json(['level' => 'error','message' => '请输入标题','data' => []]);
        if (!$classify_id)
            return response()->json(['level'=>'error','message'=>'请选择分类']);
//        if (!$industry)
//            return response()->json(['level'=>'error','message'=>'请选择行业']);
        if (!$content)
            return response()->json(['level' => 'error','message' => '请输入内容','data' => []]);

        $demand=Demands::whereTitle($title)->whereStatus(0)->first();
        if ($demand)
            return response()->json(['level' => 'error','message' => '重复发布','data' => []]);

        $UserXUnit = UserXUnit::whereUserId($adminUser->id)->first();
//        if(!$UserXUnit)
//            return response()->json(['level' => 'error','message' => '系统错误']);
        if ($UserXUnit)
            $unit = Units::whereId($UserXUnit->unit_id)->first();
        else $unit=0;
//        if(!$unit)
//            return response()->json(['level' => 'error','message' => '单位不存在']);

        //判断是否优先审核
        $isPriorityReview = 0;
        $priorityReviewVipRule = VipRule::whereMark('priority_review')->first();
        if($priorityReviewVipRule){
            $userBindVipPackageList = CommonManager::judgeVipPackageXRule($priorityReviewVipRule->id,$adminUser->id);
            if($userBindVipPackageList){
                $isPriorityReview = 1;
            }
        }

        $demand=new Demands();
        $demand->user_id            =$adminUser->id;
        $demand->unit_id            =$unit->id;
        $demand->is_show_publisher  =$is_show_publisher;
        if ($title)
            $demand->title          =$title;
        if ($content)
            $demand->content        =$content;
        if ($recruitment)
            $demand->recruitment    =$recruitment;
        if ($salary)
            $demand->salary         =$salary;
        if ($education)
            $demand->education      =$education;
        if ($first_arrive_time)
            $demand->first_arrive_time  =$first_arrive_time;
        if ($last_arrive_time)
            $demand->last_arrive_time   =$last_arrive_time;
        if ($start_time)
            $demand->start_time         =$start_time;
        if ($end_time)
            $demand->end_time           =$end_time;
        if ($classify_id)
            $demand->classify_id        =$classify_id;
        if ($province)
            $demand->province           =$province;
        if ($city)
            $demand->city               =$city;
        if ($area)
            $demand->area               =$area;
        if ($address)
            $demand->address            =$address;
        if ($industry)
            $demand->industry_id        =$industry;
        if($isPriorityReview == 1)
            $demand->is_top             =1;
        if($isAssociationDocking == 1)
            $demand->is_association_docking =1;

        if($maxButtingNum)
            $demand->max_butting_num        = $maxButtingNum;

        $demand->budget                 = $budget;
        $demand->save();

        if (count($img_ids) > 0){
            foreach ($img_ids as $img_id) {
                $exist=DemandImg::whereDemandId($demand->id)->whereImgId($img_id)->first();
                if(!$exist){
                    $demand_img = new DemandImg();
                    $demand_img->demand_id = $demand->id;
                    $demand_img->img_id = $img_id;
                    $demand_img->save();
                }
            }
        }

        if (count($label_arr) > 0){
            foreach ($label_arr as $label){
                $label_exist=DemandAllureLabel::whereName($label)->whereDemandId($demand->id)->first();
                if (!$label_exist){
                    $thisDemandLabel          =new DemandAllureLabel();
//                $thisNewsLabel->user_id=0;
                    $thisDemandLabel->name      =$label;
                    $thisDemandLabel->demand_id =$demand->id;
                    $thisDemandLabel->save();
                }
            }
        }

        $userInfo = CommonManager::getUserBasicInfo($demand->user_id);
        $realname = !empty($userInfo['realname']) ? $userInfo['realname'] : $userInfo['nickname'];

        $newMessage = new Message();
        $newMessage->type        = 'admin';
        $newMessage->content     = $realname . "发布了【{$demand->title}】，请尽快审核";
        $newMessage->link_type   = 'service';
        $newMessage->link_id     = $demand->id;
        $newMessage->save();

        return response()->json(['level' => 'success','message' => '发布成功！','data' => $demand]);
    }

    public function delDemandByAdmin(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//        if ($adminUser->role==0)
//            return response()->json(['level' => 'error','message' => '您的权限不足！','data' => 'error']);
        $demand_id=$request->get('demand_id');
        $demand=Demands::whereId($demand_id)->first();
        if (!$demand)
            return response()->json(['level' => 'error','message' => '服务不存在']);
        $demand->delete();
        $news_X_demand=NewsXDemand::whereDemandId($demand->id)->delete();
        Comment::whereDemandId($demand_id)->delete();
        return response()->json(['level' => 'success','message' => '删除成功']);
    }

    public function getDemandDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id=$request->get('demand_id');
        if (!is_numeric($id))
            return response()->json(['level'=>'error','message'=>'参数错误','data'=>[]]);
        $demand=Demands::whereId($id)->first();
        if (!$demand)
            return response()->json(['level'=>'error','message'=>'该服务不存在','data'=>[]]);

        $classify               =Classify::whereId($demand->classify_id)->first();
        $industry               =Industries::whereId($demand->industry_id)->first();

        $imgs                   =DemandImg::whereDemandId($demand->id)->get();
        $user_info              =CommonManager::getUserBasicInfo($demand->user_id);
        $success_butt           =DemandButt::whereDemandId($id)->whereStatus(1)->first();
        $label                  =DemandAllureLabel::whereDemandId($id)->pluck('name')->toArray();
//        $butts                  =DemandButt::whereDemandId($demand->id)->orderBy('created_at','desc')->offset(0)->limit(5)->get();
        $butt_info=[];
        $url_array=[];
//        if (count($butts) > 0){
//            /** @var DemandButt $butt */
//            foreach ($butts as $butt){
//                $info=CommonManager::getUserBasicInfo($butt->user_id);
//                if ($info)
//                    array_push($butt_info,$info);
//            }
//        }


        if (count($imgs) > 0){
            foreach ($imgs as $img){
                $url=FileManager::getImgUrl($img->img_id);
                array_push($url_array,$url);
            }
        }

        $demand->classify_name  = $classify ? $classify->name :'其他';
        $demand->industry_name  = $industry ? $industry->name :'其他';
        $demand->img_array_url  = $url_array;
        $demand->user_info      = $user_info;
//        $demand->butt_info      = $butt_info;
        $demand->link_url       = '/page/test/?id='.$id;
        $demand->success_time   = $success_butt ? date_format($success_butt->updated_at,'Y-m-d H:i:s') : '未完成';
        $demand->label_arr      = $label;

        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$demand]);
    }

    public function setDemandClassify(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $name   =$request->get('name');
        $pid    =$request->get('pid');
        $sort   =$request->get('sort');
        $id     =$request->get('id');
//        $is_show     =$request->get('is_show');

        if (!$name)
            return response()->json(['level'=>'error','message'=>'请输入分类名称']);
        $classify=Classify::whereId($id)->first();
        if (!$id){
            $exist  =Classify::whereName($name)->whereType('demand')->first();
            if ($exist)
                return response()->json(['level'=>'error','message'=>'该名称已存在']);
        }

        if (!$classify)
            $classify       =new Classify();
        $classify->name =$name;
        if($pid)
            $classify->pid  =$pid;
        if ($sort)
            $classify->sort =$sort;
        $classify->type ='demand';
//        if ($is_show)
            $classify->is_show =1;
//        else
//            $classify->is_show =0;
        $classify->save();
        return response()->json(['level'=>'success','message'=>'操作成功']);
    }
    public function getDemandClassify(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//        $page       =!is_null($request->get('page'))  ? $request->get('page') : 1;
//        $limit      =!is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page_info=[
            'page'=>1,
            'limit'=>5000
        ];
//        $page=$page-1;
//        $classify=Classify::whereType('demand')->orderBy('created_at','desc')->offset($page * $limit)->limit($limit)->get();
        $classify=Classify::whereType('demand')->orderBy('sort','asc')->offset(0)->limit(5000)->get();
        $page_info['total']=Classify::whereType('demand')->count();
        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$classify]);
    }
    public function delDemandClassify(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id     =$request->get('id');
        if ($id==1){
           return response()->json(['level'=>'error','message'=>'这条不允许删除，如果有需要请联系管理员']);
        }
        $classify=Classify::whereId($id)->first();
        if (!$classify)
            return response()->json(['level'=>'error','message'=>'该分类不存在']);
        $classify->delete();
        return response()->json(['level'=>'success','message'=>'删除成功']);
    }

    //资讯
    //增改资讯类型
    public function setNewsClassify(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//        if ($adminUser->role==0)
//            return response()->json(['level' => 'error','message' => '您的权限不足！','data' => 'error']);
        $name   =$request->get('name');
        $pid    =$request->get('pid');
        $sort   =$request->get('sort');
        $id     =$request->get('id');
        $status     =$request->get('status');

        if (!$name)
            return response()->json(['level'=>'error','message'=>'请输入分类名称']);
        $classify=Classify::whereId($id)->first();
        if (!$id){
            $exist  =Classify::whereName($name)->whereType('news')->first();
            if ($exist)
                return response()->json(['level'=>'error','message'=>'该名称已存在']);
        }

        if (!$classify)
            $classify       =new Classify();
        $classify->name =$name;
        $classify->desc = '';
        if($pid)
            $classify->pid  =$pid;
        if ($sort)
            $classify->sort =$sort;
        $classify->type ='news';
        if ($status)
            $classify->status =1;
        else
            $classify->status =0;
        $classify->save();
        return response()->json(['level'=>'success','message'=>'操作成功']);

    }
    public function delNewsClassify(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//        if ($adminUser->role==0)
//            return response()->json(['level' => 'error','message' => '您的权限不足！','data' => 'error']);
        $id     =$request->get('id');

        $classify=Classify::whereId($id)->whereType('news')->first();

        if (!$classify)
            return response()->json(['level'=>'error','message'=>'该分类不存在']);

        $classify->delete();
        return response()->json(['level'=>'success','message'=>'操作成功']);
    }
    public function getNewsClassifyList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//        $is_show     =$request->get('is_show');
        $page       =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit      =!is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
        $classify=Classify::whereType('news');
        $page_info['total']=$classify->count();
        $classify=$classify->offset($page * $limit)->limit($limit)->get();

        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$classify]);

    }


    public function sendNewsByAdmin(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//        if ($adminUser->role==0)
//            return response()->json(['level' => 'error','message' => '您的权限不足！','data' => 'error']);
        $title      =$request->get('title');
        $desc       =$request->get('desc');
        $classify_id=$request->get('classify_id');
        $info       =$request->get('info');
        $img_id     =$request->get('img_id');
        $video_id   =$request->get('video_id');
        $advert_img_id  =$request->get('advert_img_id');
        $industry_id    =$request->get('industry_id');

        $sort           =$request->get('sort');
        $province       =$request->get('province');
        $city           =$request->get('city');
        $id             =$request->get('id');
        $label_arr      =$request->get('label_arr');
        $status         =$request->get('status');
        $link_demand_ids=$request->get('link_demand_ids');
        if (!$title)
            return response()->json(['level'=>'error','message'=>'请输入标题']);
//        if (!$classify_id)
//            return response()->json(['level'=>'error','message'=>'请选择分类']);
//        if (!$industry_id)
//            return response()->json(['level'=>'error','message'=>'请选择行业']);

        $exist      =News::whereTitle($title)->first();
        if ($exist){
            if (strtotime($exist->created_at) + 30 >= time()){
                return response()->json(['level'=>'error','message'=>'已发布，勿重复点击']);
            }
        }
        $news=News::whereId($id)->first();
        if (!$news)
            $news       =new News();
        $news->title    =$title;
        $news->desc     =$desc;
        $news->info     =$info;
        if ($classify_id)
            $news->classify_id  =$classify_id;
        if ($img_id)
            $news->img_id       =$img_id;
        if ($video_id)
            $news->video_id     =$video_id;
        if ($advert_img_id)
            $news->advert_img_id=$advert_img_id;
        if ($industry_id)
            $news->industry_id  =$industry_id;
        if ($sort)
            $news->sort         =$sort;
        if ($province)
            $news->province     =$province;
        if ($city)
            $news->city         =$city;
        $news->status           =$status ? 1 :0;
        $news->save();
        if (count($label_arr) > 0){
            foreach ($label_arr as $label){
                $label_exist=NewsLabel::whereName($label)->whereNewsId($news->id)->first();
                if (!$label_exist){
                    $thisNewsLabel          =new NewsLabel();
//                $thisNewsLabel->user_id=0;
                    $thisNewsLabel->name    =$label;
                    $thisNewsLabel->news_id =$news->id;
                    $thisNewsLabel->save();
                }
            }
        }

//        if (count($link_demand_ids) > 0){
//            foreach ($link_demand_ids as $link_demand_id) {
//                $exist=NewsXDemand::whereNewsId($news->id)->whereDemandId($link_demand_id)->first();
//                if (!$exist){
//                    $link_demand=new NewsXDemand();
//                    $link_demand->news_id=$news->id;
//                    $link_demand->demand_id=$link_demand_id;
//                    $link_demand->save();
//                }
//            }
//        }
        return response()->json(['level'=>'success','message'=>'发布成功','data'=>$news]);


    }
    public function delNewsByAdmin(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id             =$request->get('id');
        $news=News::whereId($id)->first();
        if (!$news)
            return response()->json(['level'=>'error','message'=>'该资讯不存在']);
        $news->delete();
        $news_label=NewsLabel::whereNewsId($id)->delete();
//        Comment::whereNewsId($id)->delete();
        return response()->json(['level'=>'success','message'=>'删除成功']);
    }
    public function changeNewsStatus(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id         =$request->get('id');

        $exist      =News::whereId($id)->first();
        if (!$exist)
            return response()->json(['level' => 'error','message' => '资讯不存在','data' =>[]]);
        $exist->status=$exist->status ? 0 : 1;
        $exist->save();
        return response()->json(['level' => 'success','message' => '操作成功','data' =>$exist->status]);
    }

    public function getNewsDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id = $request->get('id');
        $news=News::whereId($id)->first();
        if (!$news)
            return response()->json(['level'=>'error','message'=>'资讯不存在']);
        $classify   =Classify::whereId($news->classify_id)->first();
        $industry   =Industries::whereId($news->industry_id)->first();
        $label      =NewsLabel::whereNewsId($news->id)->get();
//        $link_demand_ids    =NewsXDemand::whereNewsId($news->id)->pluck('demand_id')->toArray();
        $news->classify_name= $classify ? $classify->name : '其它（该分类不存在）';
        $news->industry_name= $industry ? $industry->name : '其它（该行业不存在）';
        $news->label        = $label  ? $label : [];
        $news->img_url      =FileManager::getImgUrl($news->img_id);
        $news->video_url    =FileManager::getVideoUrl($news->video_id);
        $news->advert_img_url=FileManager::getImgUrl($news->advert_img_id);
        if($news->info){
            $newImgUrl = env("OSS_FILE_URL") . env("OSS_FILE_DIR");
            $news->info = str_replace("https://wxapp.nsitp.cn/",$newImgUrl,$news->info);
        }
        $news->news_url = '/pages/details/newsDetail/newsDetail?newsId=' . $news->id;
//        $news->official_comment =Comment::whereNewsId($news->id)->whereIsOfficial(1)->first() ? 1 :0;
//        $news->link_demand_info =Demands::whereIn('id',$link_demand_ids)->get(['id','title']);
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$news]);
    }
    public function getNewsList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $page       =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit      =!is_null($request->get('limit')) ? $request->get('limit') : 10;
        $keyword            =$request->get('keyword');
        $classify_id        =$request->get('classify_id');
//        $official_comment   =$request->get('official_comment');
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
        $news=News::whereNull('deleted_at');
        if ($keyword){
            $news=$news->where('title','like','%'.trim($keyword).'%')
                ->orWhere('info','like','%'.trim($keyword).'%')
                ->orWhere('desc','like','%'.trim($keyword).'%');
        }

        if ($classify_id)
            $news=$news->whereClassifyId($classify_id);

//        if ($official_comment){
//            if ($official_comment==1){
//                $news_ids=Comment::whereIsOfficial(1)->pluck('news_id')->toArray();
//                $news=$news->whereIn('id',$news_ids);
//            } else if ($official_comment==2){
//                $news_ids=Comment::whereIsOfficial(0)->pluck('news_id')->toArray();
//                $news=$news->whereIn('id',$news_ids);
//            }
//        }
        $page_info['total']=$news->count();
        $news=$news->orderBy('status','desc')->orderBy('updated_at','desc')->offset($page * $limit)->limit($limit)
            ->get(['id','title','img_id','desc','type','link_url','video_id','advert_img_id','browse_num',
                'attention_num','like_num','sort','status','classify_id','province','city','from','industry_id','created_at','updated_at']);
        if (count($news) > 0)
            /** @var News $item */
            foreach ($news as $item) {
                $classify   =Classify::whereId($item->classify_id)->first();
                $industry   =Industries::whereId($item->industry_id)->first();
//                $newComment =Comment::whereNewsId($item->id)->whereStatus(0)->first();
                $item->label_arr    =NewsLabel::whereNewsId($item->id)->pluck('name')->toArray();
//                $item->official_comment =Comment::whereNewsId($item->id)->whereIsOfficial(1)->first() ? 1 :0;
                $item->classify_name= $classify ? $classify->name : ($item->classify_id==0 ? '未设置' : '其它（该分类已被删除）');
                $item->industry_name= $industry ? $industry->name : ($item->industry_id==0 ? '未设置' : '其它（该分类已被删除）');
                $item->from_name    = $item->from=='wx' ? '微信同步' : '手动录入';
//                $item->new_comment  = $newComment ? 1: 0;
                $item->news_url = '/pages/details/newsDetail/newsDetail?newsId=' . $item->id;
            }

        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$news]);
    }
    public function getNewsComment(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $news_id    = !is_null($request->get('news_id')) ? $request->get('news_id') : 0;
        $page       =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit      =!is_null($request->get('limit')) ? $request->get('limit') : 10;
        $type       = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : 'default';
        $demand_id  = !is_null($request->get('demand_id')) ? $request->get('demand_id') : 0;

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
        /** @var Comment $comment */
        if($type == 'default') {
            $comments   =Comment::whereNewsId($news_id)->whereType('news')->orderBy('is_official','desc')->offset($page * $limit)->limit($limit)->get();
            $page_info['total']=Comment::whereNewsId($news_id)->whereType('news')->count();
        }elseif($type == 'demand'){
            $comments   =Comment::whereDemandId($demand_id)->whereType('demand')->orderBy('is_official','desc')->offset($page * $limit)->limit($limit)->get();
            $page_info['total']=Comment::whereDemandId($demand_id)->whereType('demand')->count();
        }else{
            return [];
        }

        if (count($comments) > 0){
            foreach ($comments as $comment){
                $comment->like_num  =CommentLike::whereCommentId($comment->id)->count();
                $comment->reply_num =Comment::whereToCommentId($comment->id)->count();
                if($comment->is_official == 1) {
                    $user_info['photo_url'] = url('images/zhang.jpg');
                    $user_info['nickname']  = "官方点评";
                    $user_info['realname']  = "官方点评";

                    $comment->user_info = $user_info;
                }else{
                    $comment->user_info =CommonManager::getUserBasicInfo($comment->user_id);
                }

                if($comment->to_comment_id == 0){
                    $comment->comment_type_name = '评论';
                }else{
                    $comment->comment_type_name = '回复';
                }

            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$comments]);
    }

    /**
     * 获取所有的评论列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAllCommentList(Request $request){
        $page       = !is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $keyword    = !is_null($request->get('keyword')) ? $request->get('keyword') : '';
        $startTime  = !is_null($request->get('start_time')) ? $request->get('start_time') : '';
        $endTime    = !is_null($request->get('end_time')) ? $request->get('end_time') : '';
        $status     = !is_null($request->get('status')) ? $request->get('status') : '';

        $page_info=[
            'page'=>$page,
            'limit'=>$limit,
            'keyword' => $keyword,
            'start_time' => $startTime,
            'end_time' => $endTime
        ];

        /** @var Comment $comment */
        $commentList = Comment::whereIsOfficial(0);

        if($keyword != ''){
            $commentIdArr = [];
            $DemandIds = Demands::whereReview(1)->where('title','like','%'.trim($keyword).'%')->pluck('id')->toArray();
            if(count($DemandIds) > 0){
                /** @var Comment $commentDemand */
                $commentDemandList = Comment::whereStatus(0)->whereIn('demand_id',$DemandIds)->get();
                if(count($commentDemandList) > 0){
                    foreach($commentDemandList as $commentDemand){
                        array_push($commentIdArr,$commentDemand->id);
                    }
                }
            }

            /** @var News $newsIds */
            $newsIds = News::where('title','like','%'.trim($keyword).'%')->pluck('id')->toArray();
            if(count($newsIds) > 0){
                /** @var Comment $commentNews */
                $commentNewsList = Comment::whereStatus(0)->whereIn('news_id',$newsIds)->get();
                if(count($commentNewsList) > 0){
                    foreach($commentNewsList as $commentNews){
                        array_push($commentIdArr,$commentNews->id);
                    }
                }
            }

            $commentList->whereIn('id',$commentIdArr);
        }

        if($status != ''){
            $commentList = $commentList->whereStatus($status);
        }

        if($startTime != '' && $endTime != ''){
            $commentList = $commentList->whereBetween('created_at',[$startTime,$endTime]);
        }

        $page_info['total'] = $commentList->count();

        $commentList = $commentList->orderBy('status','asc')->orderBy('created_at','desc')->offset(($page - 1) * $limit)->limit($limit)->get();
        if(count($commentList) > 0){
            foreach($commentList as $comment){
                $comment->user_info =CommonManager::getUserBasicInfo($comment->user_id);

                $comment->comment_name = '';
                $comment->type_name = '';
                if($comment->type == 'news'){
                    $news = News::whereId($comment->news_id)->first();
                    if($news){
                        $comment->comment_name = $news->title;
                    }

                    $comment->type_name = '资讯';
                }elseif($comment->type == 'demand'){
                    $demand = Demands::whereId($comment->demand_id)->first();
                    if($demand){
                        $comment->comment_name = $demand->title;
                    }

                    $comment->type_name = '服务';
                }

                if($comment->to_comment_id == 0){
                    $comment->comment_type_name = '评论';
                }else{
                    $comment->comment_type_name = '回复';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $commentList,'page_info' => $page_info]);
    }

    public function reviewComment(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $comment_id=$request->get('comment_id');
        $type      =$request->get('type');
        $thisComment=Comment::whereId($comment_id)->first();
        if (!$thisComment)
            return response()->json(['level'=>'error','message'=>'该评论不存在']);
        if ($type==1){
            $thisComment->status=1;
        } else if ($type==2){
            $thisComment->status=2;
        } else {
            return response()->json(['level'=>'error','message'=>'type为1或2']);
        }
        $thisComment->save();
        return response()->json(['level'=>'success','message'=>'审核成功']);
    }
    public function sendOfficialComment(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//        if ($adminUser->role==0)
//            return response()->json(['level' => 'error','message' => '您的权限不足！','data' => 'error']);
        $newsId      = !is_null($request->get('news_id')) ? $request->get('news_id') : 0;
        $demandId    = !is_null($request->get('demand_id')) ? $request->get('demand_id') : 0;
        $expertId    = !is_null($request->get('expert_id')) ? $request->get('expert_id') : 0;
        $unitId      = !is_null($request->get('unit_id')) ? $request->get('unit_id') : 0;
        $content     = !is_null($request->get('content')) ? $request->get('content') : '';
        $type        = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : 'default';

        if($content == '')
            return response()->json(['level' => 'error','message' => '请填写评论内容']);

        $newComment = new Comment();
        $newComment->user_id         = 1;
        $newComment->content         = $content;
        if($type == "default"){
            $newComment->news_id         = $newsId;
            $newComment->type            = 'news';
        }elseif($type == 'demand'){
            $newComment->demand_id       = $demandId;
            $newComment->type            = 'demand';
        }elseif($type == 'expert'){
            $newComment->expert_id       = $expertId;
            $newComment->type            = 'expert';
        }elseif($type == 'unit'){
            $newComment->unit_id         = $unitId;
            $newComment->type            = 'unit';
        }else{
            return response()->json(['level' => 'error','message' => '系统错误']);
        }

        $newComment->status          = 1;
        $newComment->is_official     = 1;
        $newComment->save();

        return response()->json(['level' => 'success','message' => '发布官方评论成功','data' => $newComment]);
    }
    public function delComment(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id     =$request->get('id');
        $comment=Comment::whereId($id)->first();
        if (!$comment)
            return response()->json(['level'=>'error','message'=>'该评论不存在']);
        $comment->delete();
        $comment_like=CommentLike::whereCommentId($id)->delete();
        return response()->json(['level'=>'success','message'=>'删除成功']);
    }

    //行业列表
    public function getIndustryList(Request $request){
        $industry=Industries::orderBy('sort','asc')->get();
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$industry]);
    }
    public function addIndustry(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $name   =$request->get('name');
        $sort   =$request->get('sort');
        $id     =$request->get('id');
        if (!$name)
            return response()->json(['level'=>'error','message'=>'请输入名称','data'=>[]]);
        $industry=Industries::whereId($id)->first();
        if (!$industry)
            $industry=new Industries();
        $industry->name=$name;
        if ($sort)
            $industry->sort=$sort;
        $industry->save();
        return response()->json(['level'=>'success','message'=>'操作成功','data'=>$industry]);
    }

    //关于我们
    public function setAboutUs(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id     =$request->get('id') ? $request->get('id') : 1;
        $title  =$request->get('title');
        $desc   =$request->get('desc');
        $content=$request->get('content');
        $status =$request->get('status');
        $aboutUs=AboutUs::whereId($id)->first();
        if (!$aboutUs)
            $aboutUs=new AboutUs();
        if ($title)
            $aboutUs->title=$title;
        if ($desc)
            $aboutUs->desc =$desc;
        if ($content)
            $aboutUs->content=$content;
//        if ($status)
            $aboutUs->status =1;
        $aboutUs->save();
        return response()->json(['level'=>'success','message'=>'操作成功','data'=>$aboutUs]);

    }
    public function getAboutUsDetail(Request $request){
        $id     =$request->get('id') ? $request->get('id') : 1;
        $aboutUs=AboutUs::whereId($id)->first();
        if($aboutUs){
            if($aboutUs->content){
                $newImgUrl = env("OSS_FILE_URL") . env("OSS_FILE_DIR");
                $aboutUs->content = str_replace("https://wxapp.nsitp.cn/",$newImgUrl,$aboutUs->content);
            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$aboutUs]);
    }

    public function setBanner(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id     =$request->get('id');

        $img_id =$request->get('img_id');
        $title  =$request->get('title');
        $link_url =$request->get('link_url');
        $link_type =$request->get('link_type') ?? 0;
        $sort   =$request->get('sort');
        $status =$request->get('status');
        $banner=Banner::whereId($id)->first();
        if (!$banner)
            $banner=new Banner();
        if ($title)
            $banner->title=$title;
        if ($img_id)
            $banner->img_id =$img_id;
        $banner->link_type = $link_type;
        if ($link_url)
            $banner->link_url=$link_url;
        if ($sort)
            $banner->sort   =$sort;
        $banner->status =1;
        $banner->save();
        return response()->json(['level'=>'success','message'=>'操作成功','data'=>$banner]);
    }
    public function getBannerList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $page       =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit      =!is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
        $banner=Banner::orderBy('created_at','desc');
        $page_info['total']=$banner->count();
        $banner     =$banner->offset($page * $limit)->limit($limit)->get();
        if (count($banner) > 0){
            foreach ($banner as $item){
                $item->img_url  =FileManager::getImgUrl($item->img_id);
            }
        }

        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$banner]);

    }
    public function getBannerDetail(Request $request){
        $id=$request->get('id') ;
        $banner=Banner::whereId($id)->first();
        if (!$banner)
            return response()->json(['level'=>'error','message'=>'banner不存在']);
        $banner->img_url=FileManager::getImgUrl($banner->img_id);
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$banner]);
    }
    public function delBanner(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id     =$request->get('id');
        $banner=Banner::whereId($id)->first();
        if (!$banner)
            return response()->json(['level'=>'error','message'=>'banner不存在']);
        $banner->delete();
        return response()->json(['level'=>'success','message'=>'删除成功']);
    }

    public function setSectionClassify(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $name      =$request->get('name');
        $pid       =$request->get('pid');
        $sort      =$request->get('sort');
        $linkUrl   =$request->get('link_url');
        $linkType =$request->get('link_type') ?? 0;
        $id        =$request->get('id');
//        $is_show    =$request->get('is_show');
        $img_id    =$request->get('img_id');
        $level     =$request->get('level');

        if (!$name)
            return response()->json(['level'=>'error','message'=>'请输入分类名称']);
        $classify=Classify::whereId($id)->first();
        if (!$id){
            $exist  =Classify::whereName($name)->whereType('section')->first();
            if ($exist)
                return response()->json(['level'=>'error','message'=>'该名称已存在']);
        }

        if (!$classify)
            $classify       =new Classify();
        $classify->name =$name;
        if($pid)
            $classify->pid  =$pid;
        if ($sort)
            $classify->sort =$sort;

        $classify->type ='section';
        $classify->link_type = $linkType;

//        if ($is_show)
            $classify->is_show =1;
        if ($img_id)
            $classify->img_id  =$img_id;
        if($linkUrl){
            $classifyId = 0;
            $classifyPos = strpos($linkUrl,'classify_id=');
            if($classifyPos != false){
                $classify->link_url = $linkUrl . '&classify_name=' . $name;
            }else{
                $classify->link_url = $linkUrl;
            }
        }
        if($level){
            $classify->level    = $level;
        }

        if(!is_null($linkUrl) && $linkUrl != '' && preg_match('/^http/',trim($linkUrl))){
            $classify->level    = 4;
        }

        $classify->save();
        return response()->json(['level'=>'success','message'=>'操作成功']);
    }

    public function getSectionClassifyList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $page       =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit      =!is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
        $classify=Classify::whereType('section');
        $page_info['total']=$classify->count();
        $classify=$classify->offset($page * $limit)->limit($limit)->get();
        if (count($classify) > 0){
            foreach ($classify as $item){
                if ($item->img_id!=0)
                    $item->img_url=FileManager::getImgUrl($item->img_id);
                else
                    $item->img_url=null;
            }
        }

        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$classify]);

    }

    /**
     * 获取栏目详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSectionClassifyDetail(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $classify=Classify::whereId($id)->whereType('section')->first();
        if($classify){
            $classify->img_url=FileManager::getImgUrl($classify->img_id);
        }

        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$classify]);
    }

    public function delSectionClassify(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id     =$request->get('id');

        $classify=Classify::whereId($id)->whereType('section')->first();

        if (!$classify)
            return response()->json(['level'=>'error','message'=>'该分类不存在']);

        $classify->delete();
        return response()->json(['level'=>'success','message'=>'操作成功']);
    }
    public function addSysMessage(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//        if ($adminUser->role==0)
//            return response()->json(['level' => 'error','message' => '您的权限不足！','data' => 'error']);
        $id      =$request->get('id');
        $title   =$request->get('title');
        $content =$request->get('content');
        $detail  =$request->get('detail');
        $img_id  =$request->get('img_id');
        $groupIds =$request->get('group_ids');

        $message=Message::whereId($id)->first();
        if (!$message)
            $message=new Message();
        if ($title)
            $message->title=$title;
        if ($content)
            $message->content=$content;
        if ($detail)
            $message->detail=$detail;
        if(is_array($groupIds) && count($groupIds) > 0){
            $message->system_message_type = 1;
        }
        if ($img_id)
            $message->img_id=$img_id;
        $message->type='system';
        $message->save();

        if(!is_array($groupIds) || (is_array($groupIds) && count($groupIds) <= 0)){
            $users_num=User::count();
            if ($users_num > 0){
                for ($i=1;$i<=$users_num;$i++){
                    $remind=MessageRemind::whereUserId($i)->whereMessageId($message->id)->first();
                    if (!$remind){
                        $remind = new MessageRemind();
                        $remind->user_id    =$i;
                        $remind->message_id =$message->id;
                        $remind->save();
                    }
                }
            }
        }else{
            $users_num = 0;
            foreach($groupIds as $groupId){
                $group = Group::whereId($groupId)->first();
                if($group){
                    $groupXUserList = GroupXUser::whereGroupId($groupId)->get();
                    if(count($groupXUserList) > 0){
                        foreach($groupXUserList as $groupXUser){
                            $remind=MessageRemind::whereUserId($groupXUser->user_id)->whereMessageId($message->id)->first();
                            if(!$remind){
                                $users_num += 1;
                                $newMessageXUser = new MessageXUser();
                                $newMessageXUser->user_id    = $groupXUser->user_id;
                                $newMessageXUser->message_id = $message->id;
                                $newMessageXUser->save();

                                $remind = new MessageRemind();
                                $remind->user_id    = $groupXUser->user_id;
                                $remind->message_id = $message->id;
                                $remind->save();
                            }
                        }
                    }
                }
            }
        }

        return response()->json(['level'=>'success','message'=>'发布成功,共发给'.$users_num.'位用户']);
    }
    public function getMessageList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $limit         = !is_null($request->get('limit')) ? $request->get('limit') : 8;
        $page          = !is_null($request->get('page')) ? $request->get('page') : 1;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];
        $messageList = Message::whereType('system');

        $pageInfo['total'] = $messageList->count();
        $page=$page-1;

        $messageList = $messageList->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();

        if(count($messageList) > 0){
            foreach($messageList as $message){
                if ($message->img_id!=0)
                    $message->img_url = FileManager::getImgUrl($message->img_id);
                else
                    $message->img_url ='';
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','page_info'=>$pageInfo,'data' => $messageList]);
    }
    public function getMessageDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id     =$request->get('id');
        $message=Message::whereId($id)->whereType('system')->first();
        if (!$message)
            return response()->json(['level'=>'error','message'=>'消息不存在']);
        if ($message->img_id)
            $message->img_url=FileManager::getImgUrl($message->img_id);
        else
            $message->img_url='';
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$message]);
    }
    public function delSysMessage(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id = $request->get('id');
        $message=Message::whereId($id)->whereType('system')->first();
        if (!$message){
            $message_remind=MessageRemind::whereMessageId($id)->delete();
            return response()->json(['level'=>'error','message'=>'删除失败，消息不存在']);
        }

        $message->delete();
        $message_remind=MessageRemind::whereMessageId($message->id)->delete();
        return response()->json(['level'=>'success','message'=>'删除成功']);
    }

    public function setStatement(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//        $id     =$request->get('id') ? $request->get('id') : 1;
        $title  =$request->get('title');
        $desc   =$request->get('desc');
        $content=$request->get('content');
//        $status =$request->get('status');
        if($content == '')
            return response()->json(['level' => 'error','message' => '请填写内容']);
        $statement=SysSetUp::whereType(2)->orderBy('created_at','desc')->first();
        if (!$statement)
            $statement=new SysSetUp();
        if ($title)
            $statement->title=$title;
        if ($desc)
            $statement->desc =$desc;
        if ($content)
            $statement->content=$content;
        $statement->status  =1;
        $statement->type    =2;
        $statement->save();
        return response()->json(['level'=>'success','message'=>'操作成功','data'=>$statement]);
    }

    public function getStatement(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $statement=SysSetUp::whereType(2)->orderBy('created_at','desc')->first();
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$statement]);
    }
    public function setStatementStatus(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $status =$request->get('status');
        $statement=SysSetUp::whereType(2)->orderBy('created_at','desc')->first();
        if (!$statement)
            return response()->json(['level'=>'error','message'=>'请先发布','data'=>$statement]);
        $statement->status=$status ? 1 : 0 ;
        $statement->save();
        return response()->json(['level'=>'success','message'=>'设置成功','data'=>$statement]);
    }

    /**
     * 设置服务条款
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setTermsService(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $title  =$request->get('title');
        $desc   =$request->get('desc');
        $content=$request->get('content');

        if($content == '')
            return response()->json(['level' => 'error','message' => '请填写内容']);

        $statement=SysSetUp::whereType(5)->first();
        if (!$statement)
            $statement=new SysSetUp();

        if ($title)
            $statement->title   = $title;
        if ($desc)
            $statement->desc    = $desc;
        if ($content)
            $statement->content = $content;
        $statement->type        = 5;
        $statement->status      = 1;
        $statement->save();
        return response()->json(['level' => 'success','message' => '操作成功','data' => $statement]);
    }

    /**
     * 获取服务条款
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getTermsService(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $statement = SysSetUp::whereType(5)->whereStatus(1)->orderBy('created_at','desc')->first();
        if($statement){
            if($statement->content){
                $newImgUrl = env("OSS_FILE_URL") . env("OSS_FILE_DIR");
                $statement->content = str_replace("https://wxapp.nsitp.cn/",$newImgUrl,$statement->content);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $statement]);
    }

    /**
     * 设置服务条款的属性
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setTermsServiceStatus(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $status = !is_null($request->get('status')) ? $request->get('status') : 0;

        $statement=SysSetUp::whereType(5)->first();
        if (!$statement)
            return response()->json(['level'=>'error','message' => '服务条款不存在']);

        $statement->status = $status;
        $statement->save();
        return response()->json(['level' => 'success','message' => '设置成功','data' => $statement]);
    }

    /**
     * 发送订阅消息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\WechatException
     */
    public function sendDemandSubscribeMessage(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $demandId = !is_null($request->get('demand_id')) ? $request->get('demand_id') : 0;

        $demand = Demands::whereId($demandId)->whereReview(1)->whereIsShop(1)->first();
        if(!$demand)
            return response()->json(['level' => 'error','message' => '发送失败']);

        $userInfo = CommonManager::getUserBasicInfo($demand->user_id);

        $demandTitle = $demand->title;
        $demandName  = $userInfo ? $userInfo['realname'] : ($userInfo['nickname'] ? $userInfo['nickname'] : '' );
        $time        = date("Y-m-d H:i:s",$demand->updated_at->timestamp);

        $userList = User::whereRole(0)->get();
        if(count($userList) > 0){
            foreach($userList as $user){
                WechatLogin::weSendSubscribeMessage('demand',$user->wx_openid,$demand->id,$demandTitle,$demandName,$time);
            }
        }

        return response()->json(['level' => 'success','message' => '发送成功']);
    }

    /**
     * 获取专家预约列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getExpertAppointList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $limit         = !is_null($request->get('limit')) ? $request->get('limit') : 8;
        $page          = !is_null($request->get('page')) ? $request->get('page') : 1;
        $status        = $request->get('status');
        $keyword       = $request->get('keyword');

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];
        $page=$page-1;

//        if($adminUser->role != 1)
//            return response()->json(['level'=>'error','message'=>'无权限查看，请联系管理员处理！',"data"=>"no_permission"]);

        $appoint = AppointExpert::orderBy('id','desc');

        if ($status==1 || $status==2 || $status==3){
            if ($status==3)
                $appoint=$appoint->whereStatus(0);
            else
                $appoint=$appoint->whereStatus($status);
        }
        if (trim($keyword)){
            $expert_ids=Experts::where('realname','like','%'.trim($keyword).'%')->pluck('id')->toArray();
            $appoint=$appoint->whereIn('expert_id',$expert_ids);
        }

        $pageInfo['total'] = $appoint->count();
        $appoint=$appoint->offset($page * $limit)->limit($limit)->get();
        if (count($appoint) > 0){
            foreach ($appoint as $item){
                $expert_name=Experts::whereId($item->expert_id)->first();
                $item->expert_name=$expert_name ? $expert_name->realname :'专家不存在';
            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$pageInfo,'data'=>$appoint]);

    }

    public function confirmAppoint(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id     =$request->get('id');
//        $status = $request->get('status');
        if (!$id)
            return response()->json(['level'=>'error','message'=>'参数错误']);
        $thisAppoint=AppointExpert::whereId($id)->first();
        if (!$thisAppoint)
            return response()->json(['level'=>'error','message'=>'该预约不存在']);
        if ($thisAppoint->status!=0)
            return response()->json(['level'=>'error','message'=>'已经处理过了']);
        $thisAppoint->status=1;
        $thisAppoint->save();
        return response()->json(['level'=>'success','message'=>'处理成功']);

    }

    public function syncNewsMaterialFromWeChat(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $this->dispatch(new syncWXMaterial());
        return response()->json(['level' => 'success','message' => '已发起后台同步，请耐心等待']);
//        $limit  = !is_null($request->get('limit')) ? $request->get('limit') : 8;
//        $page   = !is_null($request->get('page')) ? $request->get('page') : 1;
//        $type   = $request->get('type');
//        $pageInfo = [
//            'limit' => $limit,
//            'page' => $page,
//            'total'=>0
//        ];
//        $type='news';
//        if (in_array($type,['image','video','voice','news'])){
//            $result=WechatLogin::getMaterial($type,$page,$limit);
//            if (!$result)
//                return response()->json(['level' => 'error','message' => '获取失败','data'=>$result]);
//            if (isset($result->errcode))
//                return response()->json(['level' => 'error','message' => '获取失败','data'=>$result]);
//            $pageInfo['total']=$result->total_count;
//            $data=$result->item;
//            return response()->json(['level'=>'success','message'=>'获取成功','data'=>$data]);
//
//        }
    }

    public function delUser(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $user_id=$request->get('user_id');
        if (!is_numeric($user_id))
            return response()->json(['level'=>'error','message'=>'用户id错误']);

        $thisUser=User::whereId($user_id)->first();

        $date=date('Y-m-d H:i:s');
        if (!$thisUser)
            return response()->json(['level'=>'error','message'=>'用户不存在']);
        $thisUser->phone        =$thisUser->phone.'-用户已删除'.$date;
//        $thisUser->wx_unionid   =$thisUser->wx_unionid.'-用户已删除'.$date;
        $thisUser->wx_openid    =$thisUser->wx_openid.'-用户已删除'.$date;
        $thisUser->wx_session_key    =$thisUser->wx_session_key.'-用户已删除'.$date;
        $thisUser->user_key     =$thisUser->user_key.'-用户已删除'.$date;
        $thisUser->status       =0;
        $thisUser->save();
        UserInfo::whereUserId($thisUser->id)->delete();
//        $userAuth   =UnitAuth::whereUserId($thisUser->id)->first();//这个据说不用了
        UserXUnit::whereUserId($thisUser->id)->delete();
        Experts::whereUserId($thisUser->id)->delete();
        GroupXUser::whereUserId($thisUser->id)->delete();
        PersonalAuth::whereUserId($thisUser->id)->delete();
        UnitAuth::whereUserId($thisUser->id)->delete();
        UnitSettledApply::whereUserId($thisUser->id)->delete();
        DemandButt::whereUserId($thisUser->id)->delete();
        $demandList = Demands::whereUserId($thisUser->id)->get();
        if(count($demandList) > 0){
            foreach($demandList as $demand){
                DemandButt::whereDemandId($demand->id)->delete();
                $demand->delete();
            }
        }

//        if ($userAuth){
//            $userAuth->wx_openid    =$userAuth->wx_openid.'-用户已删除'.$date;
//            $userAuth->save();
//            $userAuth->delete();
//        }
        $thisUser->delete();

        return response()->json(['level'=>'success','message'=>'删除成功']);
    }

    public function unDelUser(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        $sign       =$request->get('sign');
        if(!$adminUser && $sign!=md5(date('Y-m-d H:00:00')))
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $user_id    =$request->get('user_id');
        $phone      =$request->get('phone');
        if (!$user_id && !$phone)
            return response()->json(['level'=>'error','message'=>'参数错误']);
        $user=User::withTrashed()->whereId($user_id)->first();
        if ($user){
            $thisUser=User::withTrashed()->whereId($user_id)->first();
            if ($thisUser){
                if ($thisUser->delete_at==null || $thisUser->status==1)
                    return response()->json(['level'=>'error','message'=>'该用户是正常用户，无需恢复']);

                $user=User::withTrashed()->where('phone','like',substr($user->phone,0,11).'%')->count();
                if ($user > 1)
                    return response()->json(['level'=>'error','message'=>'用户已重新注册,请手动恢复数据']);
            }
        } else {
            $user=User::withTrashed()->where('phone','like',$phone.'%')->count();
            if ($user === 1){
                $thisUser=User::withTrashed()->where('phone','like',$phone.'-用户已删除'.'%')->first();
                if ($thisUser){
                    if ($thisUser->delete_at==null || $thisUser->status==1)
                        return response()->json(['level'=>'error','message'=>'该用户是正常用户，无需恢复']);
                }
            } else {
                if ($user == 0)
                    return response()->json(['level'=>'error','message'=>'无法通过手机号找到用户']);
                if ($user > 1)
                    return response()->json(['level'=>'error','message'=>'用户已重新注册,请手动恢复数据']);
                return response()->json(['level'=>'error','message'=>'未知错误']);
            }
        }
        //TODO 恢复数据
        UserInfo::withTrashed()->whereUserId($thisUser->id)->restore();
        UserXUnit::withTrashed()->whereUserId($thisUser->id)->restore();
        Experts::withTrashed()->whereUserId($thisUser->id)->restore();
        GroupXUser::withTrashed()->whereUserId($thisUser->id)->restore();
        PersonalAuth::withTrashed()->whereUserId($thisUser->id)->restore();
        UnitSettledApply::withTrashed()->whereUserId($thisUser->id)->restore();
        //TODO 恢复用户
        $thisUser->phone=substr($thisUser->phone,0,11);
//        $thisUser->wx_unionid   =substr($thisUser->wx_unionid,0,28);
        $thisUser->wx_openid    =substr($thisUser->wx_openid,0,28);
        $thisUser->wx_session_key=substr($thisUser->wx_session_key,0,24);
        $thisUser->user_key     =substr($thisUser->user_key,0,32);
        $thisUser->status       =1;
        $thisUser->save();
        $thisUser->restore();
        return response()->json(['level'=>'success','message'=>'操作成功']);
    }

    public static function syncWXMaterial(){
        $result=WechatLogin::getMaterial('news',0,20);
        if (!$result)
            return false;
        if (isset($result->errcode))
            return false;
        $total  =$result->total_count;
        $data   =$result->item;
        //TODO 存入数据库
        self::insertNews($data);
        Log::error(1);
        //TODO 继续获取
        if ($total > 20){
            //TODO 限制获取数量
//            $total=1000;
            $times=ceil($total/20);
            for ($i=1;$i<=$times;$i++){
                $result=WechatLogin::getMaterial('news',$i,20);
                if ($result){
                    if (!isset($result->errcode)){
                        $data   =$result->item;
                        //TODO 存入数据库
                        self::insertNews($data);
                        Log::error($i);
                    }
                }
            }
        }
        return true;
    }
    public static function insertNews($data){
        if (count($data)>0){
            foreach ($data as $item){
                $item->media_id;//素材id
                $thisMediaNumber=News::whereMediaId($item->media_id)->count();
                if (count($item->content->news_item) > 0){
                    foreach ($item->content->news_item as $news_item){
                        $exist=News::whereTitle($news_item->title)->whereFrom('wx')->first();
                        if (!$exist){
                            $wxNews=new News();
                            $wxNews->title=$news_item->title;
                            $wxNews->desc=$news_item->digest;
                            $wxNews->info=$news_item->content;
                            if (!empty($news_item->thumb_url)){
                                $thumb_contents=file_get_contents($news_item->thumb_url);
                                if ($thumb_contents){
                                    $fileName='wx_sync_'.trim($news_item->title).'_thumb.jpg';
                                    $fileModel=FileManager::saveFileByFileContent($thumb_contents,$fileName);
                                    if($fileModel){
                                        $imageModel = Images::whereFileId($fileModel->id)->first();
                                        if(!$imageModel){
                                            $imageModel = new Images();
                                            $imageModel->file_id = $fileModel->id;
                                            $imageModel->img_name= $fileName;
                                            $imageModel->img_type= $fileModel->file_type;
                                            $imageModel->save();
                                        }
                                        $wxNews->img_id=$imageModel->id;
                                    }
                                }
                            }

                            $wxNews->from='wx';
                            $wxNews->media_id=$item->media_id;
                            $wxNews->save();
                        }
                    }
                }
            }
        }
        return true;
    }
    public function sendDemandByModelMsg(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $result=$this->dispatch(new sendModelMsg());
        return response()->json(['level'=>'success','message'=>'请求成功']);
    }
    public function getUserOpenId(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $data=WechatModelMsg::getUserList();
        return response()->json(['level'=>'success','message'=>'处理成功','data'=>$data]);
    }

    public function getAdminMessageList(Request $request){
        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 1;
        $type  = !is_null($request->get('type')) ? $request->get('type') : '';

        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)

        $pageInfo = [
            'limit' => $limit ,
            'page'  => $page
        ];

        if($adminUser->role == 1){
            $adminMessageList = Message::whereType('admin');
        }else{
            $adminMessageList = Message::whereType('manager')->whereToUserId($adminUser->id);
        }

        if($type !== ''){
            $adminMessageList->whereIsRead($type);
        }

        $pageInfo['total'] = $adminMessageList->count();

        $adminMessageList = $adminMessageList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $adminMessageList,'page_info' => $pageInfo]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setAlreadyRead(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $adminMessage = Message::whereId($id)->first();
        if($adminMessage){
            if($adminMessage->is_read == 0){
                $adminMessage->is_read = 1;
                $adminMessage->save();
            }
        }else{
            $adminMessageList = Message::whereType('admin')->whereIsRead(0)->get();
            if(count($adminMessageList) > 0){
                foreach($adminMessageList as $adminMessage){
                    $adminMessage->is_read = 1;
                    $adminMessage->save();
                }
            }
        }

        return response()->json(['level' => 'success','message' => '操作成功','data' => $adminMessage]);
    }

    public function getAiRecords(Request $request){
        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 1;

        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $pageInfo = [
            'limit' => $limit ,
            'page'  => $page
        ];

        $pageInfo['total'] = AiRecord::count();

        $allAiRecords = AiRecord::orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();

        if(count($allAiRecords) > 0){
            foreach ($allAiRecords as $allAiRecord){
                $userInfo = UserInfo::whereUserId($allAiRecord->user_id)->first();
                if($userInfo){
                    $userInfo->photo_url = FileManager::getImgUrl($userInfo->photo_id);
                }
                $allAiRecord->user_info = $userInfo;

                $allAiRecord->score = $allAiRecord->score . "%";

                $allAiRecord->img_url = FileManager::getImgUrl($allAiRecord->img_id);
            }
        }

        return response()->json(['level' => 'success','message' => '操作成功','data' => $allAiRecords,'page_info' => $pageInfo]);
    }

    public function getAiScoreRule(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $allAiScoreRules = AiScoreRule::all();

        if(count($allAiScoreRules) > 0){
            foreach ($allAiScoreRules as $allAiScoreRule){
                switch ($allAiScoreRule->type_str){
                    case "taise":
                        $allAiScoreRule->type_str="苔色";
                        break;
                    case "taizhi":
                        $allAiScoreRule->type_str="苔质";
                        break;
                    case "shese":
                        $allAiScoreRule->type_str="舌色";
                        break;
                    case "shemian":
                        $allAiScoreRule->type_str="舌型";
                        break;
                }
            }
        }

        return response()->json(['level' => 'success','message' => '操作成功','data' => $allAiScoreRules]);
    }
}
